package com.gym.core.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gym.core.date.DateFormatUtils;

/**
 * 序列化，反序列化
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-1-5 下午8:34:44
 */
public class SerializeUtils {
	private static final Logger logger = LoggerFactory.getLogger(DateFormatUtils.class);

	
	/**
	 *  序列化
	 * @param o
	 * @return
	 */
	 public static ByteArrayOutputStream toSerialize(Object o){
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream out = null;
		try{
			out = new ObjectOutputStream(bos);
			out.writeObject(o);
		}catch(Exception e){
			logger.info("CloneObjectUtil error : ",e);
		}finally{
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					logger.error("toSerialize {}",o,e);
				}
			}
		}
		
		return bos;
	}
	
	 /**
	  * 反序列化
	  * @param bos
	  * @return
	  */
	public static Object deSerialize(ByteArrayOutputStream bos){
		Object o = null;
		ObjectInputStream in = null;
		try{
			in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
			o = in.readObject();
		}catch(Exception e){
			logger.error("deSerialize error :",e);
		}finally{
			if(in != null){
				try {
					in.close();
				} catch (IOException e) {
					logger.error("deSerialize close error :",e);
				}
			}
		}
		
		return o;
	}
	
}
